package cc.linker.steplink.crm.merchant.service.impl;

import cc.linker.steplink.crm.commons.constant.TlPayConstant;
import cc.linker.steplink.crm.commons.constant.WcPayConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.WcPayProperties;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.merchant.dao.acs.MerchantInfoDao;
import cc.linker.steplink.crm.merchant.dao.acs.PlatformSetNameDao;
import cc.linker.steplink.crm.merchant.service.acs.PlatformSetNameService;
import cc.linker.steplink.crm.merchant.util.FTPUtil;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PlatformSetNameServiceImpl implements PlatformSetNameService {

    @Autowired
    private HttpService httpService;
    @Autowired
    private PlatformSetNameDao platformSetNameDao;
    @Autowired
    private MerchantInfoDao MerchantInfoDao;
    @Autowired
    private WcPayProperties wcPayProperties;
    @Autowired
    private CommonsService commonsService;

    @Override
    public void setName(Map<String, Object> map) {
        platformSetNameDao.setName(map);
    }

    @Override
    public Map<String, Object> lookSetting(String orgId) {
        return platformSetNameDao.lookSetting(orgId);
    }

    @Override
    public void savePaySetting(Map<String, Object> map) {
        platformSetNameDao.savePaySetting(map);
    }

    @Override
    public void updatePaySetting(Map<String, Object> map) {
        platformSetNameDao.updatePaySetting(map);
    }

    @Override
    public Object capitalAccountApply(Map<String, Object> param) throws Exception {
        String result = httpService.doPost(wcPayProperties.getAcsurl() + TlPayConstant.USER_OPEN_PAY_ACCOUNT, JSONObject.toJSONString(param), WcPayConstant.JSON);
        LOGGER.info("capitalAccountApply-->" + result);
        JSONObject object = JSONObject.parseObject(result);
        if (object != null) {
            if (("200").equals(object.getString("code"))) {
                JSONObject data = JSONObject.parseObject(object.getString("data"));
                if (("30").equals(data.getString("status"))) {
                    //中金返回成功
                }
                return data;
            } else {
                throw GlobalException.build(object.get("msg").toString());
            }
        } else {
            throw GlobalException.build("开通失败");
        }
    }

    @Override
    public boolean ifExist(Map<String, Object> map) {
        Integer num = platformSetNameDao.ifOrgExist(map);
        if (num > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Object capitalAccountInfo() {
        String customerId = "LINKER";
        Map<String, Object> data = new HashMap<>(1);
        Map<String, Object> status = platformSetNameDao.getCapitalAccountInfo(customerId);
        if (status == null || status.get("accountStatus") == null) {
            //未开通
            data.put("accountStatus", 0);
            data.put("bankStatus", 0);
            data.put("corporationName", null);
        } else {
            data = status;
        }
        return data;
    }

    @Override
    public String getLinkerZjorgId() {
        String linkerZjorgId = platformSetNameDao.getLinkerZjorgId();
        if (linkerZjorgId == null) {
            linkerZjorgId = "005366";
        }
        return linkerZjorgId;
    }

    @Override
    public Map getImage(String orgId) {
        return platformSetNameDao.getImage(orgId);
    }

    @Override
    public List<Map<String, Object>> getMould(String orgId, String type) {
        return platformSetNameDao.getMould(orgId, type);
    }

    @Override
    public void delMould(Map<String, Object> param) {
        platformSetNameDao.delMould(param);
    }

    @Override
    public void setImage(Map<String, Object> param) {
        if (platformSetNameDao.ifOrgExist(param) > 0) {
            platformSetNameDao.setImage(param);
        } else {
            platformSetNameDao.addImage(param);
        }
    }

    @Override
    public void addMould(Map<String, Object> param) {
        platformSetNameDao.addMould(param);
    }

    @Override
    public void updateNameSet(Map<String, Object> map) {
        platformSetNameDao.updateNameSet(map);
    }

    @Override
    public List<Map<String, Object>> platformList() {
        return platformSetNameDao.platformList();
    }

    @Override
    public List<Map<String, Object>> bussinessAccountList(String platformId) {
        return platformSetNameDao.bussinessAccountList(platformId);
    }

    @Override
    public Map<String, Object> getPaySetting(String orgId) {
        Map<String, Object> result = platformSetNameDao.getPaySetting(orgId);
        if (result == null) {
            Map<String, Object> temp = new HashMap<>();
            temp.put("bussinessAccount", "");
            temp.put("linkerRate", "");
            temp.put("payMode", "");
            temp.put("platformId", "");
            temp.put("unionBarleyTake", "");
            temp.put("withdrawCost", "");
            temp.put("withdrawLimit", "");
            temp.put("withdrawTakeType", "");
            temp.put("withdrawRate", "");
            temp.put("ftpServerIp", "");
            temp.put("ftpServerPort", "");
            temp.put("ftpAccount", "");
            temp.put("ftpPassword", "");
            return temp;
        } else {
            return result;
        }
    }

    @Override
    public Map getAccountByName(String bankAccountName, String customerId) {
        return platformSetNameDao.getAccountByName(bankAccountName, customerId);
    }

    @Override
    public String getModeImage(Integer king) {
        return platformSetNameDao.getModeImage(king);
    }

    @Override
    public Boolean uploadFiles(Map<String, Object> param, String orgId) {
        Map<String, Object> ftpInfo = MerchantInfoDao.getFtpInfoByOrgId(orgId);
        String ftpServerIp = ftpInfo.get("ftpServerIp").toString();
        Integer ftpServerPort = Integer.parseInt(ftpInfo.get("ftpServerPort").toString());
        String ftpAccount = ftpInfo.get("ftpAccount").toString();
        String ftpPassword = ftpInfo.get("ftpPassword").toString();

        //开户许可证图片
        List<Map<String, Object>> fileList = new ArrayList<>();
        Map<String, Object> settlement = new HashMap<>();
        settlement.put("fileUrl", param.get("licenceUrl").toString());
        settlement.put("fileName", "bank_settlement.jpg");
        //统一社会信用代码证
        Map<String, Object> license = new HashMap<>();
        license.put("fileUrl", param.get("unifiedSocialCreditUrl").toString());
        license.put("fileName", "business_license.jpg");
        //身份证背面图片
        Map<String, Object> cerificateBack = new HashMap<>();
        cerificateBack.put("fileUrl", param.get("identityBackUrl").toString());
        cerificateBack.put("fileName", "legal_cerificate_back.jpg");
        //身份证正面图片
        Map<String, Object> cerificateFront = new HashMap<>();
        cerificateFront.put("fileUrl", param.get("identityJustUrl").toString());
        cerificateFront.put("fileName", "legal_cerificate_front.jpg");
        fileList.add(settlement);
        fileList.add(license);
        fileList.add(cerificateBack);
        fileList.add(cerificateFront);
        // 调用ftp上传方法
        return FTPUtil.uploadFtp(ftpServerIp, ftpServerPort, ftpAccount, ftpPassword, param.get("customerId").toString(), fileList);
    }

    @Override
    public Boolean uploadFilesNew(Map<String, Object> param, String orgId) {
        String url = wcPayProperties.getAcsurl() + TlPayConstant.COMMON_UPLOADPICTURE;
        Map<String, Object> req = new HashMap<>();
        //调试用"yth"
        req.put("clintType", param.get("clintType"));
        req.put("customerId", param.get("infoId"));

        List<Map<String, Object>> picList = new ArrayList<>();
        Map<String, Object> settlement = new HashMap<>();
        //开户许可证图片
        settlement.put("picture", commonsService.encodeImageToBase64(param.get("licenceUrl").toString()));
        settlement.put("picType", 4);
        //统一社会信用代码证
        Map<String, Object> license = new HashMap<>();
        license.put("picture", commonsService.encodeImageToBase64(param.get("unifiedSocialCreditUrl").toString()));
        license.put("picType", 5);
        //身份证背面图片
        Map<String, Object> cerificateBack = new HashMap<>();
        cerificateBack.put("picture", commonsService.encodeImageToBase64(param.get("identityBackUrl").toString()));
        cerificateBack.put("picType", 9);
        //身份证正面图片
        Map<String, Object> cerificateFront = new HashMap<>();
        cerificateFront.put("fileUrl", commonsService.encodeImageToBase64(param.get("identityJustUrl").toString()));
        cerificateFront.put("picType", 8);
        picList.add(settlement);
        picList.add(license);
        picList.add(cerificateBack);
        picList.add(cerificateFront);
        req.put("picList", picList);
        String result;
        try {
            LOGGER.info("callTlAndReturn,request===[{}]", JSON.toJSONString(req));
            result = httpService.doPost(url, JSON.toJSONString(req), WcPayConstant.JSON);
        } catch (URISyntaxException | IOException e) {
            throw GlobalException.build("网关调用异常");
        }
        LOGGER.info(result);
        if (!StringUtils.isEmpty(result)) {
            Map<String, Object> res = (Map<String, Object>) JSON.parse(result);
            if ("200".equals(res.get("code").toString())) {
                Map<String, Object> da = (Map<String, Object>) JSON.parse(res.get("data").toString());
                if ("30".equals(da.get("status").toString())) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public String getInfoIdByAdminId(String adminId) {
        return platformSetNameDao.getInfoIdByAdminId(adminId);
    }
}
